package com.df.my_net_game.game_rpc.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
//@Component
public class RpcClient {
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;
    private final String host;
    private final int port;

    public RpcClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect() throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
//                        pipeline.addLast(new GRpcEncoder());
//                        pipeline.addLast(new GRpcDecoder());
                        pipeline.addLast(new RpcClientHandler());
                    }
                });

        ChannelFuture future = bootstrap.connect(host, port).sync();
        channel = future.channel();
        log.info("RPC client connected to {}:{}", host, port);
    }

    public void sendRequest(Object request) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(request);
        } else {
            log.error("Connection is not active, cannot send request");
        }
    }

    public void shutdown() {
        if (channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
        log.info("RPC client shutdown");
    }

    @ChannelHandler.Sharable
    private static class RpcClientHandler extends SimpleChannelInboundHandler<Object> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
            // 处理服务器响应
//            if (msg instanceof GRpcResp) {
//                GRpcResp response = (GRpcResp) msg;
//                ResponseFuture future = ResponseFuture.getFuture(response.getRequestId());
//                if (future != null) {
//                    future.setResponse(response);
//                }
//            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            log.error("RPC client exception", cause);
            ctx.close();
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            log.warn("Connection lost, trying to reconnect...");
            // 实现重连逻辑
            super.channelInactive(ctx);
        }
    }
}
